<template>
  <ContentWrap>
    <div class="flex justify-end mb-20px">
      <el-button link type="primary" @click="searchType = 'senior'" v-if="searchType == 'ordinary'">
        <Icon color="#0052cc" :size="14" class="mr-5px" icon="ep:search" />
        高级筛选</el-button
      >
      <el-button type="primary" link @click="searchType = 'ordinary'" v-else>
        <Icon color="#0052cc" :size="14" class="mr-5px" icon="ep:search" />普通筛选</el-button
      >
    </div>
    <AdvancedScreening v-if="searchType == 'senior'" page="call_record" @search="handleAdavance" />
    <!-- 搜索工作栏 -->
    <el-form
      v-if="searchType == 'ordinary'"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
      label-position="left"
    >
      <el-form-item label="负责人" prop="ownerUserId">
        <el-select class="!w-260px" v-model="queryParams.ownerUserId" clearable filterable>
          <el-option
            v-for="item in userOptions"
            :key="parseInt(item.id)"
            :label="item.nickname"
            :value="parseInt(item.id)"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="坐席工号" prop="agentNumber">
        <el-input
          v-model="queryParams.agentNumber"
          placeholder="请输入坐席工号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-260px"
        />
      </el-form-item>
      <el-form-item label="被叫号码" prop="callee">
        <el-input
          v-model="queryParams.callee"
          placeholder="请输入被叫"
          clearable
          @keyup.enter="handleQuery"
          class="!w-260px"
        />
      </el-form-item>

      <el-form-item label="外呼类型">
        <el-select
          v-model="queryParams.callType"
          placeholder="请选择外呼类型"
          clearable
          class="!w-260px"
        >
          <el-option label="点呼" value="1" />
          <el-option label="群呼" value="2" />
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="录音生成状态" prop="downloadStatus">
        <el-select
          v-model="queryParams.downloadStatus"
          placeholder="请选择录音生成状态"
          clearable
          class="!w-260px"
        >
          <el-option label="已生成" value="1" />
          <el-option label="未生成" value="0" />
        </el-select>
      </el-form-item>

      <el-form-item label="文字生成状态" prop="transStatus">
        <el-select
          v-model="queryParams.transStatus"
          placeholder="请选择状态"
          clearable
          class="!w-260px"
        >
          <el-option label="已生成" value="1" />
          <el-option label="未生成" value="0" />
          <el-option label="生成失败" value="-1" />
          <el-option label="进行中" value="9" />
        </el-select>
      </el-form-item>
      <el-form-item label="话单状态">
        <el-select
          v-model="queryParams.resultCode"
          placeholder="请选择状态"
          clearable
          class="!w-260px"
        >
          <el-option label="成功" value="success" />
          <el-option label="漏接" value="leak" />
          <el-option label="失败" value="faile" />
          <el-option label="错误" value="illegal" />
        </el-select>
      </el-form-item>
      <el-form-item label="呼叫结果">
        <el-select
          v-model="queryParams.resultType"
          placeholder="请选择状态"
          clearable
          class="!w-260px"
        >
          <el-option label="呼叫成功" value="1" />
          <el-option label="播放语音时挂断" value="10" />
          <el-option label="播放语音完挂断" value="11" />
          <el-option label="系统线路异常" value="90" />
          <el-option label="黑名单或拦截" value="91" />
          <el-option label="空号或号码错误" value="92" />
          <el-option label="客户拒接或挂断" value="93" />
          <el-option label="客户忙或未接听" value="94" />
          <el-option label="坐席忙线未接听" value="95" />
          <el-option label="呼叫失败" value="99" />
        </el-select>
      </el-form-item>
    </el-form>
    <div class="flex justify-between">
      <div>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>

        <el-button
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['call:record:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </div>
    </div>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-tag
      @close="handleCloseTag(tag.label)"
      v-for="(tag, index) in sortTagList"
      :key="index"
      closable
      class="sortTag mr-10px"
    >
      {{ tag.name }} <el-icon v-if="tag.sort != 'desc'"><CaretTop /></el-icon
      ><el-icon v-else><CaretBottom /></el-icon>
    </el-tag>
    <el-tabs v-model="activeName" @tab-click="handleTabClick" v-if="searchType == 'ordinary'">
      <el-tab-pane label="我负责的" name="1" />
      <el-tab-pane label="下属负责的" name="2" />
      <el-tab-pane label="全部" name="0" />
    </el-tabs>
    <el-table
      :header-cell-style="getRowClass"
      ref="sortTable"
      @sort-change="sortChange"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      border
    >
      <el-table-column label="主叫" align="left">
        <template #default="scope">
          <div class="text-12px">
            <div>员工：{{ scope.row.ownerUserName }}</div>
            <div>坐席：{{ scope.row.agentNumber }}</div>
            <div>手机：{{ scope.row.telephone }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="被叫" align="left">
        <template #default="scope">
          <div class="text-12px">
            <div>号码：{{ scope.row.encryptCallee }}</div>
            <div>来源：{{ sourceMap[scope.row.source] || '其他' }}</div>
            <div
              >名称：
              <el-link type="primary" @click="seeDetail(scope.row)">{{
                scope.row.sourceName
              }}</el-link>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column sortable="custom" label="呼叫结果" align="center" prop="resultType">
        <template #default="scope">
          <div class="flex justify-center flex-col">
            <el-tag v-if="scope.row.resultCode == 'success'" type="success">成功</el-tag>
            <el-tag v-else-if="scope.row.resultCode == 'leak'" type="warning">漏接</el-tag>
            <el-tag v-else-if="scope.row.resultCode == 'fail'" type="danger">失败</el-tag>
            <el-tag v-else-if="scope.row.resultCode == 'illegal'" type="info">错误</el-tag>
            <span class="text-#172b4d text-13px">{{ resultTypeMap[scope.row.resultType] }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        sortable="custom"
        label="应答时间"
        align="center"
        prop="startTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        sortable="custom"
        label="挂断时间"
        align="center"
        prop="endTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column sortable="custom" label="时长" align="left" prop="callSecond">
        <template #default="scope">
          <div class="text-12px">
            通话: {{ scope.row.callSecond }} 秒; 计费: {{ scope.row.callMinute }} 分
          </div>
        </template></el-table-column
      >
      <el-table-column
        sortable="custom"
        width="150px"
        label="录音和文字"
        align="left"
        prop="downloadStatus"
      >
        <template #default="scope">
          <div>
            <div
              >录音：<el-tag v-if="scope.row.downloadStatus" type="success">已生成</el-tag>
              <el-tag v-else type="info">未生成</el-tag></div
            >
            <div
              >文字：<el-tag v-if="scope.row.transStatus == 1" type="success">已生成</el-tag>
              <el-tag v-if="scope.row.transStatus == 0" type="info">未生成</el-tag>
              <el-tag v-if="scope.row.transStatus == -1" type="danger">生成失败</el-tag>
              <el-tag v-if="scope.row.transStatus == 9" type="info">进行中</el-tag>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        sortable="custom"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column align="center" prop="remark" label="备注"> </el-table-column>
      <el-table-column label="操作" align="center" width="180px" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="openDetail(scope.row.id)"> 详情 </el-button>
          <el-button
            link
            type="primary"
            @click="downloadAudio(scope.row)"
            :disabled="!scope.row.recordUrl"
          >
            下载录音
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <DetailDes ref="detailRef" @success="getList" />
  <!-- crm详情 -->
  <CrmSpec ref="crmSpec" @getPage="getList" />
  <!--企业详情  -->
  <EnterpriseDetails ref="companyDetail" @refresh-val="detailRefreList" />
</template>

<script setup lang="ts">
import { CaretTop, CaretBottom } from '@element-plus/icons-vue'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { RecordApi, RecordVO } from '@/api/call/record'
import DetailDes from './detail.vue'
import EnterpriseDetails from '@/views/ent/components/EnterpriseDetaill/index.vue'
import AdvancedScreening from '@/views/crm/components/AdvancedScreening/index.vue'
import * as AdvancedQueryApi from '@/api/crm/advancedQuery/index.ts'
import * as UserApi from '@/api/system/user'
const userOptions = ref<UserApi.UserVO[]>([]) // 用户列表
import dayjs from 'dayjs'

/** 通话录音 列表 */
defineOptions({ name: 'Record' })

const message = useMessage() // 消息弹窗
const searchType = ref('ordinary')

const sourceMap = {
  ent: '企业大数据',
  clue: '线索',
  customer: '客户',
  contact: '联系人',
  none: '手拨'
}

const loading = ref(true) // 列表的加载中
const list = ref<RecordVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  telephone: undefined,
  agentNumber: undefined,
  callee: undefined,
  startTime: [],
  endTime: [],
  callSecond: undefined,
  callMinute: undefined,
  reqNo: undefined,
  ownerUserId: undefined,
  downloadStatus: undefined,
  createTime: [],
  sortFields: {},
  sortStr: JSON.stringify({ createTime: 'desc' }),
  sceneType: '1', // 默认和 activeName 相等
  transStatus: undefined,
  resultType: undefined,
  callType: undefined,
  resultCode: undefined
})
const activeName = ref('1') // 列表 tab

const resultTypeMap = {
  1: '呼叫成功',
  10: '播放语音时挂断',
  11: '播放语音完挂断',
  90: '系统线路异常',
  91: '黑名单或拦截',
  92: '空号或号码错误',
  93: '客户拒接或挂断',
  94: '客户忙或未接听',
  95: '坐席忙线未接听',
  99: '呼叫失败'
}
let closeTag = ref()
let isClearSort = ref(false)
const sortTagList = reactive([])
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const crmSpec = ref(null)
/** tab 切换 */
const handleTabClick = (tab: TabsPaneContext) => {
  queryParams.sceneType = tab.paneName
  handleQuery()
}
const companyDetail = ref(null)
/** 线索的详情*/
const seeDetail = (item) => {
  if (item.source == 'none' || item.source == '') {
    return
  }
  // crm
  if (item.source == 'clue' || item.source == 'customer' || item.source == 'contact') {
    crmSpec.value.setDrawer(true, item.source, item.sourceId, [])
    // 企业大数据
  } else if (item.source == 'ent') {
    companyDetail.value.setDrawer(true, item.sourceId, null, null)
  }
}
const detailRefreList = () => {}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    if (Object.keys(queryParams.sortFields).length > 0) {
      queryParams.sortStr = JSON.stringify(queryParams.sortFields)
    }

    let data
    if (searchType.value == 'senior') {
      if (!queryParams.params) return
      const obj = {
        pageNo: queryParams.pageNo,
        pageSize: queryParams.pageSize,
        params: queryParams.params
      }
      data = await AdvancedQueryApi.callAdvancePage(obj)
    } else {
      if (queryParams.params) delete queryParams.params
      data = await RecordApi.getRecordPage(queryParams)
    }
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const initPage = () => {
  if (searchType.value == 'ordinary') {
    queryParams.pageNo = 1
    queryParams.params = null
    getList()
  }
}
/**线索的高级查询*/
const handleAdavance = async (item) => {
  queryParams.pageNo = 1
  queryParams.params = JSON.parse(item.params)
  getList()
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
} /** 关闭标签 */
const handleCloseTag = (label) => {
  delete queryParams.sortFields[label]
  sortTagList.splice(
    sortTagList.findIndex((i) => i.label === label),
    1
  )
  handleQuery()
  closeTag.value = label
}

/** 标签排序 */
const sortChange = (column) => {
  queryParams.sortFields[column.prop] = column.order == 'descending' ? 'desc' : 'asc'
  let label = column.column.label
  if (sortTagList.findIndex((i) => i.name === label) < 0) {
    sortTagList.push({
      name: label,
      sort: column.order == 'descending' ? 'desc' : 'asc',
      label: column.prop
    })
  } else {
    sortTagList.splice(
      sortTagList.findIndex((i) => i.name === label),
      1,
      {
        name: label,
        sort: column.order == 'descending' ? 'desc' : 'asc',
        label: column.prop
      }
    )
  }

  handleQuery()
  closeTag.value = ''
}

/** 处理样式 */
const getRowClass = ({ row, column, rowIndex, columnIndex }) => {
  if (column.property == closeTag.value) {
    column.order = ''
  }
}

const sortTable = ref()
/** 重置按钮操作 */
const resetQuery = () => {
  searchType.value = 'ordinary'
  queryParams.sortFields = {}
  sortTagList.length = 0
  closeTag.value = ''
  sortTable.value.clearSort()
  queryParams.resultType = undefined
  if (queryParams.params) delete queryParams.params
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 下载录音
const downloadAudio = (row) => {
  if (row.recordUrl) {
    const link = document.createElement('a')
    link.href = row.recordUrl
    link.setAttribute('download', 'recording.mp4')
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }
}

/** 打开详情*/
const detailRef = ref()
const openDetail = (id: number) => {
  detailRef.value.open(id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await RecordApi.exportRecord(queryParams)
    download.excel(data, '通话录音.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
const getUserOption = async () => {
  userOptions.value = await UserApi.getSimpleUserList()
}
/** 初始化 **/
onMounted(() => {
  queryParams.createTime = [
    dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
    dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss')
  ]
  getList()
  getUserOption()
})
</script>
